package com.msb.apiDriver.service;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.msb.apiDriver.remote.ServiceDriverUserClient;
import com.msb.apiDriver.remote.VerificationCodeClient;
import com.msb.internalcommon.constant.CommonStatusEnum;
import com.msb.internalcommon.constant.DriverCarConstants;
import com.msb.internalcommon.constant.IdentityConstant;
import com.msb.internalcommon.constant.TokenConstants;
import com.msb.internalcommon.dto.ResponseResult;
import com.msb.internalcommon.reponese.DriverUserExistsResponse;
import com.msb.internalcommon.reponese.NumberCodeResponse;
import com.msb.internalcommon.reponese.TokenResponse;
import com.msb.internalcommon.request.VerificationCodeDTO;
import com.msb.internalcommon.util.JwtUtils;
import com.msb.internalcommon.util.RedisPrefixUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Auther: jiudianliu
 * @Date: 2023/7/4 - 07 - 04 - 13:52
 * @Description: com.msb.apiDriver.service
 * @version: 1.0
 */
@Service
@Slf4j
public class VerificationCodeService {

    @Autowired
    ServiceDriverUserClient serviceDriverUserClient ;

    @Autowired
    VerificationCodeClient verificationCodeClient ;

    @Autowired
    private StringRedisTemplate stringRedisTemplate ;

    public ResponseResult checkAndsendVerificationCode( String driverPhone ){
        //查询service-driver-user 该手机号的司机是否存在
        ResponseResult<DriverUserExistsResponse> driverUserExistsResponseResponseResult = serviceDriverUserClient.checkDriver(driverPhone);
        DriverUserExistsResponse data = driverUserExistsResponseResponseResult.getData();
        int ifExists = data.getIfExists();
        if (ifExists == DriverCarConstants.DRIVER_NOT_EXISTS){
            return ResponseResult.fail(CommonStatusEnum.DRIVER_NOT_EXISTS.getCode() , CommonStatusEnum.DRIVER_NOT_EXISTS.getValue());
        }
        log.info(driverPhone + "司机存在");
        //获取验证码
        ResponseResult<NumberCodeResponse> numberCodeResult = verificationCodeClient.getNumberCode(6);
        NumberCodeResponse numberCodeResponse = numberCodeResult.getData();
        int numberCode = numberCodeResponse.getNumberCode();
        log.info("验证码" + numberCode);
        //调用第三方发送验证码


        //存入redis
        String key = RedisPrefixUtils.generatorKeyByPhone(driverPhone, IdentityConstant.DRIVER_IDENTITY);
        stringRedisTemplate.opsForValue().set( key , numberCode+" " , 2 , TimeUnit.MINUTES );
        return ResponseResult.success("");
    }

    /**
     * 校验验证码
     * @param driverPhone  司机手机号
     * @param verificationCode  验证码
     * @return
     */
    public ResponseResult checkCode (String driverPhone , String verificationCode){

        // 根据手机号，去redis读取验证码
        // 生成key
        String key = RedisPrefixUtils.generatorKeyByPhone(driverPhone , IdentityConstant.DRIVER_IDENTITY);

        // 根据key获取value
        String codeRedis = stringRedisTemplate.opsForValue().get(key);
        System.out.println("Redis中的value：" + codeRedis);

        //校验验证码
        if (StringUtils.isBlank(codeRedis))
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode(), CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
        if (!verificationCode.trim().equals(codeRedis.trim())){
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode(),CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
        }

        // 颁发令牌 , 身份验证用常量值或枚举
        String accessToken = JwtUtils.generatorToken(driverPhone, IdentityConstant.DRIVER_IDENTITY, TokenConstants.ACCESS_TOKEN_TYPE);
        String refreshToken = JwtUtils.generatorToken(driverPhone, IdentityConstant.DRIVER_IDENTITY,TokenConstants.REFRESH_TOKEN_TYPE);

        // 将Token存入Redis
        //accessToken 设置过期时间为30天
        //refreshToken  设置过期时间为31天  比access多一天
        String accessTokenKey = RedisPrefixUtils.generatorTokenKey(driverPhone, IdentityConstant.DRIVER_IDENTITY , TokenConstants.ACCESS_TOKEN_TYPE);
        stringRedisTemplate.opsForValue().set(accessTokenKey , accessToken , 30 , TimeUnit.DAYS);
        String refreshTokenKey = RedisPrefixUtils.generatorTokenKey(driverPhone, IdentityConstant.DRIVER_IDENTITY , TokenConstants.REFRESH_TOKEN_TYPE);
        stringRedisTemplate.opsForValue().set(refreshTokenKey , refreshToken , 31 , TimeUnit.DAYS);

        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);
        return ResponseResult.success(tokenResponse);
    }
}
